package com.example.springdemo.config;

import com.example.springdemo.factory.EnumMvcConverterFactory;
import com.example.springdemo.interceptor.AuthInterceptor;
import com.example.springdemo.interceptor.RestResponseInterceptor;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * XrwWebMvcConfigure
 *
 * @author wenguang
 * @date 2020/11/26 10:37
 */
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DemoWebMvcConfigure implements WebMvcConfigurer {

    private final AuthInterceptor authInterceptor;

    private final RestResponseInterceptor restResponseInterceptor;

    private final EnumMvcConverterFactory enumMvcConverterFactory;

    private final ObjectMapper objectMapper;

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter =
            new MappingJackson2HttpMessageConverter();

        mappingJackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(0, mappingJackson2HttpMessageConverter);
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(authInterceptor)
            .addPathPatterns("/**")
            .excludePathPatterns(
                "/swagger**/**",
                "/webjars/**",
                "/v3/**",
                "/v2/**"
            )
            .excludePathPatterns("/", "/error", "/csrf");

        registry.addInterceptor(restResponseInterceptor);
    }

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // org.springframework.core.convert.support.GenericConversionService.ConvertersForPair.add
        // this.converters.addFirst(converter);
        // 所以我们自定义的会放在前面
        registry.addConverterFactory(enumMvcConverterFactory);
    }

}
